package com.itheima.service;

import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.Login;
import com.itheima.utils.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 林晓伟
 */
@Service
public class LoginService {
    @Resource
    private RedisTemplate<String, String> stringRedisTemplate;
    @Resource
    private LoginMapper loginMapper;

    /**
     * F02-登录接口
     *
     * @param login 手机号和验证码
     */
    public Login a(Login login) {
        //获取验证码
        String code = stringRedisTemplate.opsForValue().get("code");
        String code1 = login.getCode();
        if (code1.equals(code)) {
            //验证code通过后，生成token存入redis
            HashMap<String, String> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("code", code1);
            String token = JWTUtils.getToken(objectObjectHashMap);
            stringRedisTemplate.opsForValue().set("clientToken", token, 7, TimeUnit.HOURS);
            //获取rdis里的验证码生成的token，set到表里
            String clientToken = stringRedisTemplate.opsForValue().get("clientToken");
            login.setToken(clientToken);
            login.setSort(1);
            loginMapper.a(login);
            return loginMapper.sel(login.getPhone());
        }
        return null;
    }
}
